import { useIntersectionObserver, useIntervalFn } from '@vueuse/core'
import { onBeforeUnmount, onMounted, onUnmounted, ref } from 'vue'

export const useHeimaScroll = () => {
  const y = ref(0)
  const onScroll = () => {
    y.value = document.documentElement.scrollTop
  }
  // 挂载事件
  onMounted(() => {
    window.addEventListener('scroll', onScroll)
  })
  // 销毁事件
  onBeforeUnmount(() => {
    window.addEventListener('scroll', onScroll)
  })
  return { y }
}

// 封装通用的数据懒加载api
export function useLazyData(apiFn: () => void) {
  // 通过ref获得组件实例
  const target = ref(null)
  const { stop } = useIntersectionObserver(
    // target是观察的目标dom容器，必须是dom容器，而且是vue3绑定的dom对象
    target,
    // isIntersecting是否进入可视区域，true是进入
    ([{ isIntersecting }]) => {
      if (isIntersecting) {
        stop()
        apiFn()
      }
    },
    {
      threshold: 0
    }
  )
  return target
}

// 封装一个倒计时功能
export function useCountDown(count: number = 60) {
  const time = ref(0)
  const { pause, resume } = useIntervalFn(
    () => {
      time.value--
      if (time.value === 0) {
        pause()
      }
    },
    1000,
    { immediate: false }
  )

  // 组件销毁时清除定时器
  onUnmounted(() => {
    pause()
  })

  const start = () => {
    time.value = count
    resume()
  }

  return {
    time,
    start
  }
}
